<?php
namespace App\Http\Controllers\Common;

use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;


class PhoneController extends Controller
{

    public function __construct(){}

    /*判断opensms*/
    public function is_opensms(Request $request){


        /*self::send();*/
    }

    public function urlSend($weburl,$arr)
    {

        //只支持单条请求
        $url = $weburl.'?xh=&dstime=';
        foreach ($arr as $key => $value) {
            $url .= "&{$key}={$value}";
        }
        // echo $url;
        //优先使用curl ，curl 效率更高，并且支持异步
        if (function_exists('curl_init')) {
            $ch = curl_init();
            $timeout = 5;
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
            $file_contents = curl_exec($ch);
            curl_close($ch);
        } else {
            $file_contents = file_get_contents($url);
        }
        $status = explode(",", $file_contents);
        //file_put_contents('sms1130.txt', date('Ymd H:i:s', time()) . $url.'|'.$file_contents . PHP_EOL, FILE_APPEND);
        return $status[0];

    }




    /*发送短信*/
    public function send(Request $request)
    {

        $mobile = $request->phone;
        $phone_config = require_once __DIR__.'/../../../Common/phone_config.php';
        $msg = rand(100000,999999);
        $content = "你的手机验证码为：".$msg."【贷齐乐】";	//内容
        $weburl = $phone_config['smsweburl'];
        $arr = array("username"=>$phone_config['smsuser'],"password"=>$phone_config['smspwd'],"content"=>$content,"productid"=>$phone_config['productid'],"mobile"=>$mobile);

        $result = $this->urlSend($weburl,$arr);

        if($result){
            \Illuminate\Support\Facades\Session::put('validate_code',$msg);
            \Illuminate\Support\Facades\Session::put('mobile',$mobile);
            \Illuminate\Support\Facades\Session::save();

            $msg = '短信发送成功';
            $code = 200;
            $data = true;
        }else{
            $msg = '短信发送失败';
            $code = 101;
            $data = false;
        }

        return response()->json([
            'code' => $code,
            'message' => $msg,
            'data' => $data,
        ]);
    }



    // 前台获取初始用户数据
    public  function find(Request $request)
    {
        $phone = $request->phone;
        $is = User::where('phone',$phone)->first();
        if(empty($is)){
            $msg = '不存在';
            $code = 200;
            $data = false;
        }else{
            $msg = '存在';
            $code = 200;
            $data = true;
        }

        return response()->json([
            'code' => $code,
            'message' => $msg,
            'data' => $data
        ]);
    }

    // 前台获取初始用户数据
    public function register(Request $request)
    {
        $sms_code = $request->sms_code;
        $phone = $request->phone;
        $password = $request->password;
        $inviter = $request->inviter;


        $scode = $request->session()->get('validate_code','');//取出信息
        $sphone = $request->session()->get('mobile','');//取出信息

        if($scode != $sms_code || $sphone !=$phone){
            return response()->json([
                'code' => 101,
                'message' => '验证码错误',
                'data' => false
            ]);
        }
        $top_id =null;
        if(!empty($inviter)){

            $top = User::where('inviter',$inviter)->first();
            if(!empty($top)){
                $top_id =$top->id;
            }
        }


        $user_id = User::insertGetId([
            'phone'=>$phone,
            'top_id'=>$top_id,
            'password'=>bcrypt($password),
        ]);

        if($user_id){
            User::find($user_id)->update([
                'inviter'=>$this->createCode($user_id)
            ]);
        }

        return response()->json([
            'code' => 200,
            'message' => '注册成功',
            'data' => true
        ]);
    }

    //生成邀请码
    public function createCode($user_id) {
        static $source_string = 'E5FCDG3HQA4B1NOPIJ2RSTUV67MWX89KLYZ';
        $num = $user_id;
        $code = '';
        while ( $num > 0) {
            $mod = $num % 35;
            $num = ($num - $mod) / 35;
            $code = $source_string[$mod].$code;
        }
        if(empty($code[3]))
            $code = str_pad($code,4,'0',STR_PAD_LEFT);
        return $code;
    }



}
